/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.co.cij.grails.validation;

import groovy.lang.GroovyObject;

import java.util.Map;

import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.validation.HibernateDomainClassValidator;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.context.MessageSource;
import org.springframework.validation.Errors;

/**
 * 追加制約も検証するクラス
 * @author Shiro Kasahara
 * @since 0.1
 */
public class InterimDomainClassValidator extends HibernateDomainClassValidator {

	private static final String ERRORS_PROPERTY = "errors";

	private MessageSource messageSource;
	private Map additionalConstraints = null;

	/**
	 * @param messageSource
	 *            The messageSource to set.
	 */
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void setAdditionalConstraints(Map additionalConstraints) {
		this.additionalConstraints = additionalConstraints;
	}

	/**
	 * @see org.codehaus.groovy.grails.validation.CascadingValidator#validate(Object,
	 *      org.springframework.validation.Errors, boolean)
	 */
	public void validate(Object obj, Errors errors, boolean cascade) {
		GrailsDomainClass domainClass = getDomainClass();
		if (!domainClass.getClazz().isInstance(obj))
			throw new IllegalArgumentException("Argument [" + obj
					+ "] is not an instance of [" + domainClass.getClazz()
					+ "] which this validator is configured for");

		BeanWrapper bean = new BeanWrapperImpl(obj);

		Map constrainedProperties = domainClass.getConstrainedProperties();

		GrailsDomainClassProperty[] persistentProperties = domainClass
				.getPersistentProperties();

		for (int i = 0; i < persistentProperties.length; i++) {
			GrailsDomainClassProperty persistentProperty = persistentProperties[i];
			String propertyName = persistentProperty.getName();
			if (constrainedProperties.containsKey(propertyName)) {
				validatePropertyWithConstraint(propertyName, obj, errors, bean,
						constrainedProperties);
			}
			if (!(Boolean) bean.getPropertyValue("interim")
					&& additionalConstraints.containsKey(propertyName)) {
				validatePropertyWithConstraint(propertyName, obj, errors, bean,
						additionalConstraints);
			}

			if ((persistentProperty.isAssociation() || persistentProperty
					.isEmbedded())
					&& cascade) {
				cascadeToAssociativeProperty(errors, bean, persistentProperty);
			}
		}

		if (obj instanceof GroovyObject) {
			((GroovyObject) obj).setProperty(ERRORS_PROPERTY, errors);
		} else {
			InvokerHelper.setProperty(obj, ERRORS_PROPERTY, errors);
		}

	}

	/**
	 * @see org.springframework.validation.Validator#validate(Object,
	 *      org.springframework.validation.Errors)
	 */
	public void validate(Object obj, Errors errors) {
		validate(obj, errors, false);
	}

	private void validatePropertyWithConstraint(String propertyName,
			Object obj, Errors errors, BeanWrapper bean,
			Map constrainedProperties) {
		int i = propertyName.lastIndexOf(".");
		String constrainedPropertyName;
		if (i > -1) {
			constrainedPropertyName = propertyName.substring(i + 1,
					propertyName.length());
		} else {
			constrainedPropertyName = propertyName;
		}
		ConstrainedProperty c = (ConstrainedProperty) constrainedProperties
				.get(constrainedPropertyName);
		c.setMessageSource(this.messageSource);
		c.validate(obj, bean.getPropertyValue(constrainedPropertyName), errors);
	}

}
